import requests
import hmac
import hashlib
import time


def get_binance_server_time():
    url = "https://api.binance.com/api/v3/time"
    response = requests.get(url)
    if response.status_code == 200:
        server_time = response.json()['serverTime']
        return server_time
    else:
        raise Exception("无法获取币安服务器时间")


def diagnose_api_issue(api_key, api_secret, testnet=True):
    """诊断API问题的综合函数"""
    base_url = "https://testnet.binance.vision" if testnet else "https://api.binance.com"

    print("=== API问题诊断开始 ===")

    # 测试1: 检查基本连接和API密钥有效性
    print("\n1. 测试基本连接和API密钥...")
    try:
        # 首先测试公开接口（不需要API密钥）
        public_response = requests.get(f"{base_url}/api/v3/ping", timeout=10)
        if public_response.status_code == 200:
            print("✅ 币安API服务正常")
        else:
            print("❌ 币安API服务可能有问题")

        # 测试需要API密钥的接口
        # timestamp = int(time.time() * 1000)
        timestamp = get_binance_server_time()
        endpoint = "/api/v3/account"
        params = f"timestamp={timestamp}&recvWindow=5000"

        signature = hmac.new(
            api_secret.encode('utf-8'),
            params.encode('utf-8'),
            hashlib.sha256
        ).hexdigest()

        url = f"{base_url}{endpoint}?{params}&signature={signature}"
        headers = {"X-MBX-APIKEY": api_key}

        response = requests.get(url, headers=headers, timeout=10)

        if response.status_code == 200:
            print("✅ API密钥有效，具有读取权限")
            return True
        else:
            error_data = response.json()
            print(f"❌ API请求失败: {error_data}")

            # 根据错误代码提供具体建议
            if error_data.get('code') == -2015:
                return diagnose_specific_issue(api_key, base_url)
            else:
                print(f"错误代码: {error_data.get('code')}")
                print(f"错误信息: {error_data.get('msg')}")
                return False

    except Exception as e:
        print(f"❌ 诊断过程中出现异常: {e}")
        return False


def diagnose_specific_issue(api_key, base_url):
    """诊断特定问题"""
    print("\n=== 详细问题诊断 ===")

    issues_found = []

    # 检查IP限制
    print("2. 检查IP限制...")
    try:
        # 获取当前公网IP
        ip_response = requests.get('https://httpbin.org/ip', timeout=5)
        current_ip = ip_response.json()['origin']
        print(f"当前IP地址: {current_ip}")

        # 检查IP是否可能被限制
        test_response = requests.get(f"{base_url}/api/v3/time", timeout=5)
        if test_response.status_code == 200:
            print("✅ 当前IP可以访问币安API")
        else:
            issues_found.append("IP可能被限制")
            print("❌ 当前IP可能无法访问币安API")
    except:
        print("⚠️  无法确定IP状态")

    # 检查API密钥权限
    print("3. 检查API密钥状态...")
    # 这里无法直接通过API检查密钥状态，但可以提供建议
    issues_found.append("API密钥可能无效或权限不足")

    print(f"\n发现的问题: {issues_found}")
    return False


# 使用诊断函数

API_KEY = "oMlYVBgANplqH7XilK0rzJ47r7p1R3MWoywVNBYOGvj5UHYXebQnxZjX9kLpdd5V"
API_SECRET = "8587vRjV45QsPPXhlrn3vcBdUwQJFA6HIBqfaVbJO7UqhhqTcVrQCR4GEO6w4OtN"
# diagnose_api_issue(API_KEY, API_SECRET, testnet=False)

"""
API密钥
2oPh0dpc09V6L9LeoE9RRqf4XJGiaYqivkxlMsYf7NgpYcjZZUo70KNMjSyQUBqn
密钥:
BIaS4LA4BZT5zyIne9e0chYJqzxV4TdipTdY3VGEIQCHk1QWc5kUbH2KzmtgOI2H
"""


diagnose_specific_issue(API_KEY,  "https://api.binance.com")